package cars;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class CarOwner {

	/**统计车的所有权、型号和类型的数量
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		if (args.length!=2) {
			System.err.println("user path err!");
			System.exit(-1);
		}
		Job job=new Job(new Configuration(),"carowner");
		job.setJarByClass(CarOwner.class);
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));
		
		job.setMapperClass(coMap.class);
		job.setReducerClass(coReduce.class);
		
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(IntWritable.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		job.waitForCompletion(true);
	}
	public static class coMap extends Mapper<LongWritable,Text,Text,IntWritable>{
		protected void map(LongWritable key, Text value, org.apache.hadoop.mapreduce.Mapper<LongWritable,Text,Text,IntWritable>.Context context) throws java.io.IOException ,InterruptedException {
			String[] lines = value.toString().split("\t");
			if (lines.length>10 && lines[5]!="" && lines[9]!="" && lines[5]!=null && lines[9]!=null && lines[11]!="") {
				String carmodel=lines[5].trim();
				String ownership=lines[9].trim();
				context.write(new Text(carmodel+"-"+ownership),new IntWritable(1));
			}
		};
	}
	public static class coReduce extends Reducer<Text, IntWritable,Text,IntWritable>{
		protected void reduce(Text k2, java.lang.Iterable<IntWritable>values, org.apache.hadoop.mapreduce.Reducer<Text,IntWritable,Text,IntWritable>.Context context) throws java.io.IOException ,InterruptedException {
			int sum=0;
			for (IntWritable count : values) {
				sum+=count.get();
			}
			context.write(k2,new IntWritable(sum));
		};
	}

}
